function websocket() {
    this.socket = null;
    this.code = new Date().getTime() + '' + Math.floor(Math.random() * (1000 + 1));
    this.options = {
        url: getWsPath,
        dataType: 'json',
        onmessage: function (msg) {
            return msg;
        },
        onopen: function (msg) {
            return msg;
        },
        onclose: function (msg) {
            return msg;
        },
        onerror: function (msg) {
            return msg;
        }
    };
}

websocket.prototype.init = function (options) {
    if (!window.WebSocket) {
        window.WebSocket = window.MozWebSocket;
    }
    if (window.WebSocket) {
        this.socket = new WebSocket(getWsPath() + '/' + this.code);
    } else {
        console.log('当前浏览器不支持WebSocket');
        return;
    }
    if (options) {
        options = $.extend(this.options, options);
        this.socket.onerror = function (event) {
            options.onopen(event.data);
        };
        this.socket.onopen = function (event) {

        };
        this.socket.onmessage = function (event) {
            // if (options.dataType = 'json') {
            //     options.onmessage($.parseJSON(event.data));
            // } else {
            //     options.onmessage(event.data);
            // }
            options.onmessage(event.data);
        };
        this.socket.onerror = function (event) {

        };
        this.socket.onclose = function (event) {
            options.onclose(event.data);
        };
        window.onbeforeunload = function () {
            if (options.socket) {
                options.socket.close();
            }
        }
    }
};
websocket.prototype.send = function (msg) {
    if (!window.WebSocket) {
        return;
    }
    if (this.socket.readyState == WebSocket.OPEN) {
        if (typeof msg == 'string') {
            this.socket.send(msg);
        } else {
            msg['code'] = this.code;
            msg.paramsln = JSON2.stringify(msg.paramsln);
            this.socket.send(JSON2.stringify(msg));
        }
    } else {
        console.log('connection unopend');
    }
};
websocket.prototype.close = function () {
    if (!window.WebSocket) {
        return;
    }
    if (null == this.socket) {
        this.socket.close();
    }
};

function getWsPath() {
    var host = window.location.host;
    var path = window.document.location.pathname;
    var projectName = path.substring(0, path.substr(1).indexOf('/') + 1);
    return 'ws://' + host + projectName + '/ws';
}